package cn.wolfcode.crm.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对controller的增强
 */
@ControllerAdvice
public class HandlerExceptionUtil {

    /**
     * 针对不同的异常来进行处理(没有权限的异常)
     */
    @ExceptionHandler(UnauthorizedException.class)
    public void handlerException(HttpServletResponse response, HandlerMethod method) throws IOException {
        //但是对于ajax请求是没有效果的
        //判断是否是ajax请求(有ResponseBody注解的),如果是就返回json,如果不是就跳转页面
        ResponseBody annotation = method.getMethodAnnotation(ResponseBody.class);
        if(annotation!=null){
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(new ObjectMapper()
                    .writeValueAsString(new JSONResult().mark("您没有权限操作!")));

        }else {
            response.sendRedirect("/nopermission.jsp");
        }

    }

}
